package cn.imvc.app.models;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.User;
import cn.imvc.app.repositories.UserRepository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;
@Service
public class UserModelImpl implements UserModel {

	@Autowired
	private UserRepository userRepository;
	
	public Page<User> find(ViewRequest viewRequest) {
		return userRepository.findAll(ModelUtil.OrderByIdDesc(viewRequest));
	}
	
	public Page<User> find(String select,String from,ViewRequest viewRequest) {
		return userRepository.findAll(select, from, viewRequest);
	}

	public User get(int id) {
		return userRepository.findOne(id);
	}

	public User save(User entity) {	
		return userRepository.saveAndFlush(entity);
	}

	public User update(int id ,User entity) {
		User loaduser=get(id);
		if(entity.getPassword().equals("")){
			BeanUtils.copyProperties(entity, loaduser, new String[]{"id","username","password"});
		}else{
			BeanUtils.copyProperties(entity, loaduser, new String[]{"id","username"});
		}
		
		return userRepository.saveAndFlush(loaduser);
	}

	public void delete(int id) {
		userRepository.delete(id);
		
	}

	public User get(String username) {
		return userRepository.findByUsername(username).get(0);
	}

	public List<User> find() {
		
		return userRepository.findAll(new Sort(Direction.DESC,"order"));
	}

	public User getSessionUser() {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username="";
		if (principal instanceof UserDetails) {
		   username = ((UserDetails)principal).getUsername();
		} else {
		   username = principal.toString();
		}
		return get(username);
	}


}
